<script setup lang="ts" jsx>
import { ref, reactive, h } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag, NTree } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
import { fetchOpsInstanceList, deleteOpsInstance, batchDeleteOpsInstances, stopOpsInstance, rerunOpsInstance, batchStopOpsInstances, batchRerunOpsInstances } from '@/service/api';
import { useTable } from '@/hooks/common/table';
import InstanceLogModal from './modules/instance-log-modal.vue';
import InstanceTreeDrawer from './modules/instance-tree-drawer.vue';
import InstancePerformanceModal from './modules/instance-performance-modal.vue';

const { columns, data, loading, pagination, getData, searchParams, resetSearchParams } = useTable({
  apiFn: fetchOpsInstanceList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: '',
    status: '',
    triggerType: '',
    startTimeBegin: null,
    startTimeEnd: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center'
    },
    {
      key: 'id',
      title: '实例ID',
      align: 'center',
      width: 100
    },
    {
      key: 'jobName',
      title: '作业名称',
      align: 'center',
      minWidth: 150
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 120,
      render: row => {
        const statusMap: Record<string, { type: 'success' | 'error' | 'warning' | 'info'; text: string }> = {
          RUNNING: { type: 'info', text: '运行中' },
          SUCCESS: { type: 'success', text: '成功' },
          FAILED: { type: 'error', text: '失败' },
          STOPPED: { type: 'warning', text: '已停止' }
        };
        const status = statusMap[row.status] || { type: 'info', text: row.status };
        return h(NTag, { type: status.type }, { default: () => status.text });
      }
    },
    {
      key: 'triggerType',
      title: '触发类型',
      align: 'center',
      width: 120,
      render: row => {
        const typeMap: Record<string, string> = {
          MANUAL: '手动',
          SCHEDULE: '定时',
          DEPENDENCY: '依赖'
        };
        return typeMap[row.triggerType] || row.triggerType;
      }
    },
    {
      key: 'startTime',
      title: '开始时间',
      align: 'center',
      width: 180
    },
    {
      key: 'endTime',
      title: '结束时间',
      align: 'center',
      width: 180
    },
    {
      key: 'duration',
      title: '执行时长',
      align: 'center',
      width: 120,
      render: row => {
        if (!row.duration) return '-';
        const seconds = Math.floor(row.duration / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        if (hours > 0) return `${hours}h ${minutes % 60}m`;
        if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
        return `${seconds}s`;
      }
    },
    {
      key: 'retryCount',
      title: '重试次数',
      align: 'center',
      width: 100
    },
    {
      key: 'actions',
      title: '操作',
      align: 'center',
      width: 280,
      render: row => {
        return h(NSpace, { justify: 'center' }, {
          default: () => [
            h(NButton, { 
              size: 'small', 
              onClick: () => handleViewTree(row.id) 
            }, { default: () => '查看树形' }),
            
            h(NButton, { 
              size: 'small', 
              onClick: () => handleViewLogs(row.id) 
            }, { default: () => '查看日志' }),
            
            row.status === 'RUNNING' && h(NPopconfirm, {
              onPositiveClick: () => handleStop(row.id)
            }, {
              default: () => '确认停止该实例？',
              trigger: () => h(NButton, { 
                size: 'small', 
                type: 'warning' 
              }, { default: () => '停止' })
            }),
            
            (row.status === 'FAILED' || row.status === 'STOPPED') && h(NButton, {
              size: 'small',
              type: 'primary',
              onClick: () => handleRerun(row.id)
            }, { default: () => '重跑' }),
            
            row.status !== 'RUNNING' && h(NPopconfirm, {
              onPositiveClick: () => handleDelete(row.id)
            }, {
              default: () => '确认删除该实例？',
              trigger: () => h(NButton, { 
                size: 'small', 
                type: 'error' 
              }, { default: () => '删除' })
            })
          ].filter(Boolean)
        });
      }
    }
  ]
});

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '运行中', value: 'RUNNING' },
  { label: '成功', value: 'SUCCESS' },
  { label: '失败', value: 'FAILED' },
  { label: '已停止', value: 'STOPPED' }
];

// 触发类型选项
const triggerTypeOptions = [
  { label: '全部', value: '' },
  { label: '手动', value: 'MANUAL' },
  { label: '定时', value: 'SCHEDULE' },
  { label: '依赖', value: 'DEPENDENCY' }
];

// 选中的行
const checkedRowKeys = ref<number[]>([]);

// 实例日志弹窗
const logModalRef = ref<InstanceType<typeof InstanceLogModal>>();
const handleViewLogs = (instanceId: number) => {
  logModalRef.value?.open(instanceId);
};

// 实例树形结构抽屉
const treeDrawerRef = ref<InstanceType<typeof InstanceTreeDrawer>>();
const handleViewTree = (instanceId: number) => {
  treeDrawerRef.value?.open(instanceId);
};

// 性能指标弹窗
const performanceModalRef = ref<InstanceType<typeof InstancePerformanceModal>>();
const handleViewPerformance = () => {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请选择实例');
    return;
  }
  performanceModalRef.value?.open(checkedRowKeys.value);
};

// 停止实例
const handleStop = async (instanceId: number) => {
  await stopOpsInstance(instanceId);
  window.$message?.success('停止成功');
  getData();
};

// 重跑实例
const handleRerun = async (instanceId: number) => {
  const newInstanceId = await rerunOpsInstance(instanceId);
  window.$message?.success(`重跑成功，新实例ID: ${newInstanceId}`);
  getData();
};

// 删除实例
const handleDelete = async (instanceId: number) => {
  await deleteOpsInstance(instanceId);
  window.$message?.success('删除成功');
  getData();
};

// 批量停止
const handleBatchStop = async () => {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要停止的实例');
    return;
  }
  const successCount = await batchStopOpsInstances(checkedRowKeys.value);
  window.$message?.success(`成功停止 ${successCount} 个实例`);
  checkedRowKeys.value = [];
  getData();
};

// 批量重跑
const handleBatchRerun = async () => {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要重跑的实例');
    return;
  }
  const successCount = await batchRerunOpsInstances(checkedRowKeys.value);
  window.$message?.success(`成功重跑 ${successCount} 个实例`);
  checkedRowKeys.value = [];
  getData();
};

// 批量删除
const handleBatchDelete = async () => {
  if (checkedRowKeys.value.length === 0) {
    window.$message?.warning('请选择要删除的实例');
    return;
  }
  const successCount = await batchDeleteOpsInstances(checkedRowKeys.value);
  window.$message?.success(`成功删除 ${successCount} 个实例`);
  checkedRowKeys.value = [];
  getData();
};

// 搜索
const handleSearch = () => {
  getData();
};

// 重置
const handleReset = () => {
  resetSearchParams();
  getData();
};
</script>

<template>
  <div class="h-full overflow-hidden">
    <NCard title="运维管理" :bordered="false" class="h-full card-wrapper">
      <template #header-extra>
        <NSpace>
          <NButton type="primary" @click="handleViewPerformance">
            <icon-ic-round-analytics class="mr-4px text-icon" />
            性能指标
          </NButton>
          <NButton @click="getData">
            <icon-mdi-refresh class="mr-4px text-icon" :class="{ 'animate-spin': loading }" />
            刷新
          </NButton>
        </NSpace>
      </template>

      <!-- 搜索表单 -->
      <NSpace class="pb-12px" :size="16" :wrap="false">
        <NInput
          v-model:value="searchParams.jobName"
          placeholder="作业名称"
          clearable
          class="w-200px"
        />
        <NSelect
          v-model:value="searchParams.status"
          :options="statusOptions"
          placeholder="状态"
          clearable
          class="w-150px"
        />
        <NSelect
          v-model:value="searchParams.triggerType"
          :options="triggerTypeOptions"
          placeholder="触发类型"
          clearable
          class="w-150px"
        />
        <NDatePicker
          v-model:formatted-value="searchParams.startTimeBegin"
          type="datetime"
          placeholder="开始时间（起）"
          clearable
          class="w-200px"
        />
        <NDatePicker
          v-model:formatted-value="searchParams.startTimeEnd"
          type="datetime"
          placeholder="开始时间（止）"
          clearable
          class="w-200px"
        />
        <NButton type="primary" ghost @click="handleSearch">
          <icon-ic-round-search class="mr-4px text-icon" />
          搜索
        </NButton>
        <NButton @click="handleReset">
          <icon-ic-round-refresh class="mr-4px text-icon" />
          重置
        </NButton>
      </NSpace>

      <!-- 批量操作按钮 -->
      <NSpace class="pb-12px" :size="16">
        <NPopconfirm @positive-click="handleBatchStop">
          <template #trigger>
            <NButton type="warning" :disabled="checkedRowKeys.length === 0">
              <icon-ic-round-stop class="mr-4px text-icon" />
              批量停止
            </NButton>
          </template>
          确认停止选中的实例？
        </NPopconfirm>
        <NButton type="primary" :disabled="checkedRowKeys.length === 0" @click="handleBatchRerun">
          <icon-ic-round-replay class="mr-4px text-icon" />
          批量重跑
        </NButton>
        <NPopconfirm @positive-click="handleBatchDelete">
          <template #trigger>
            <NButton type="error" :disabled="checkedRowKeys.length === 0">
              <icon-ic-round-delete class="mr-4px text-icon" />
              批量删除
            </NButton>
          </template>
          确认删除选中的实例？
        </NPopconfirm>
      </NSpace>

      <!-- 数据表格 -->
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row: Api.Dataplatform.OpsInstanceDetail) => row.id"
        :scroll-x="1400"
        flex-height
        class="h-full"
      />
    </NCard>

    <!-- 实例日志弹窗 -->
    <InstanceLogModal ref="logModalRef" />

    <!-- 实例树形结构抽屉 -->
    <InstanceTreeDrawer ref="treeDrawerRef" />

    <!-- 性能指标弹窗 -->
    <InstancePerformanceModal ref="performanceModalRef" />
  </div>
</template>

<style scoped></style>
